$(function() {
	var name = $("#name"), email = $("#owener"), password = $("#permit"), rowindex = $("#rowindex"), allFields = $(
			[]).add(name).add(email).add(password).add(rowindex);

	$("#dialog-form")
			.dialog(
					{
						autoOpen : false,
						height : 450,
						width : 350,
						modal : true,
						buttons : {
							"Create/Edit" : function() {
								if (rowindex.val() == "") {//新增
									$("#roles tbody")
											.append(
													"<tr>"
															+ "<td>"
															+ name.val()
															+ "</td>"
															+ "<td>"
															+ email.val()
															+ "</td>"
															+ "<td>"
															+ password.val()
															+ "</td>"
															+ '<td><button class="EditButton" >Edit</button><button class="DeleteButton">Delete</button></td>'
															+ "</tr>");
									bindEditEvent();
								} else {//修改
									var idx = rowindex.val();
									var tr = $("#roles>tbody>tr").eq(idx);
									//$("#debug").text(tr.html());
									tr.children().eq(0).text(name.val());
									tr.children().eq(1).text(email.val());
									tr.children().eq(2).text(password.val());
								}
								$(this).dialog("close");
							},
							Cancel : function() {
								$(this).dialog("close");
							}
						},
						close : function() {
							//allFields.val( "" ).removeClass( "ui-state-error" );
							;
						}
					});

	function bindEditEvent() {
		//绑定Edit按钮的单击事件
		$(".EditButton").click(function() {
			var b = $(this);
			var tr = b.parents("tr");
			var tds = tr.children();
			//设置初始值
			name.val(tds.eq(0).text());
			email.val(tds.eq(1).text());
			password.val(tds.eq(2).text());

			var trs = b.parents("tbody").children();
			//设置行号，以行号为标识，进行修改。
			rowindex.val(trs.index(tr));

			//打开对话框
			$("#dialog-form").dialog("open");
		});

		//绑定Delete按钮的单击事件
		$(".DeleteButton").click(function() {
			var tr = $(this).parents("tr");
			tr.remove();
		});
	}
	;

	bindEditEvent();

	$("#create-role").button().click(function() {
		//清空表单域
		allFields.each(function(idx) {
			this.value = "";
		});
		$("#dialog-form").dialog("open");
	});
});
